package com.example.vup;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.rfid.reader.APIResponse;
import com.rfid.reader.IReader;
import com.rfid.reader.util.Util;
import com.rfid.reader.vup.*;

import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

  private static final String TAG = MainActivity.class.getName();
  private Button btnConnectTcp;
  private Button btnConnectUdp;
  private EditText tcpIpEdit;
  private EditText udpIpEdit;
  private Button stopAutoBtn;
  private Button startAutoBtn;
  private Button setAntBtn;
  private Button listTagBtn;
  private Button listAuto;
  private Button listAutoUdp;

  private IReader reader;

  private EditText contentEdit;

  private boolean isConnected;
  private EditText antEdit;
  private boolean isListening;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initUI();
    //IReader.setDebug(true,false);
    IReader.setLogLevel(6);

//    new Thread(){
//      @Override
//      public void run() {
//
//        for (int i = 0; i < 10; i++) {
//          IReader.startListenUdp("", 5000, new IReader.AutoModeResponseCallback() {
//            @Override
//            public void onResponse(IReader.AutoModelResponseItem autoModelResponseItem) {
//              Log.d(TAG,  autoModelResponseItem.toString());
//            }
//          });
//
//          try {
//            sleep(5000);
//          } catch (InterruptedException e) {
//            e.printStackTrace();
//          }
//
//          IReader.stopListenUdp("", 5000);
//
//          try {
//            sleep(5000);
//          } catch (InterruptedException e) {
//            e.printStackTrace();
//          }
//        }
//
//      }
//    }.start();
  }

  private void initUI() {

    btnConnectTcp = findViewById(R.id.connect_tcp);
    btnConnectTcp.setOnClickListener(this);
    btnConnectUdp = findViewById(R.id.connect_udp);
    btnConnectUdp.setOnClickListener(this);
    tcpIpEdit = findViewById(R.id.ip_tcp);
    udpIpEdit = findViewById(R.id.ip_udp);
    stopAutoBtn = findViewById(R.id.stop_auto);
    stopAutoBtn.setOnClickListener(this);
    startAutoBtn = findViewById(R.id.start_auto);
    startAutoBtn.setOnClickListener(this);
    setAntBtn = findViewById(R.id.set_ant);
    listTagBtn = findViewById(R.id.list_tag);
    listAuto = findViewById(R.id.listen_auto);
    listAutoUdp = findViewById(R.id.listen_auto_udp);
    contentEdit = findViewById(R.id.editTextText);

    setAntBtn.setOnClickListener(this);
    listTagBtn.setOnClickListener(this);
    listAuto.setOnClickListener(this);
    listAutoUdp.setOnClickListener(this);
    antEdit = findViewById(R.id.ant);

    Button stopListenAuto = findViewById(R.id.stop_listen_auto);
    Button stopListenAutoUdp = findViewById(R.id.stop_listen_auto_udp);

    stopListenAutoUdp.setOnClickListener(this);
    stopListenAuto.setOnClickListener(this);

    Button disconnectBtn = findViewById(R.id.disconnect);
    disconnectBtn.setOnClickListener(this);
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
      case R.id.connect_tcp:
        connectTcp();
        break;
      case R.id.connect_udp:
        connectUdp();
        break;
      case R.id.start_auto:
        startAuto();
        break;
      case R.id.stop_auto:
        stopAuto();
        break;
      case R.id.set_ant:
        setAnt();
        break;
      case R.id.list_tag:
        listTag();
        break;
      case R.id.listen_auto:
        listenAuto();
        break;
      case R.id.listen_auto_udp:
        listenUdpAuto();
        break;
      case R.id.stop_listen_auto:
        stopListenAuto();
        break;
      case R.id.stop_listen_auto_udp:
        stopListenUdpAuto();
        break;
      case R.id.disconnect:
        disconnect();
        break;

    }

  }

  private void toast(String message) {
    Toast.makeText(this, message, Toast.LENGTH_LONG).show();
  }

  private void disconnect() {
    if (isConnected) {
      reader.disconnect();
      reader = null;
      isConnected = false;
      toast("disconnect ok");
    }
  }

  private void connectTcp() {
    if (isConnected) {
      Toast.makeText(this, "请勿重复连接", Toast.LENGTH_LONG).show();
      return;
    }

    String[] strs = tcpIpEdit.getText().toString().split(":");
    if (strs.length!=2) {
      Toast.makeText(this, "请输入合法ip和端口", Toast.LENGTH_LONG).show();
      return;
    }
    // vup tcp client
    reader = new TCPClient(strs[0], Integer.parseInt(strs[1]));
    // r2000 tcp client
//    reader = new R2000TCPClient(strs[0], Integer.parseInt(strs[1]);
    APIResponse<Void> rsp = reader.connect();
    if (rsp.isSuccess()) {
      Toast.makeText(this, "连接成功", Toast.LENGTH_LONG).show();
      isConnected = true;
    } else {
      Toast.makeText(this, "连接失败", Toast.LENGTH_LONG).show();
    }
  }

  private void connectUdp() {
    if (isConnected) {
      Toast.makeText(this, "请勿重复连接", Toast.LENGTH_LONG).show();
      return;
    }

    String[] strs = udpIpEdit.getText().toString().split(":");
    if (strs.length!=2) {
      Toast.makeText(this, "请输入合法ip和端口", Toast.LENGTH_LONG).show();
      return;
    }
    reader = new UDPClient(strs[0], Integer.parseInt(strs[1]));
    // r2000 udp client
//    reader = new R2000UDPClient(strs[0], Integer.parseInt(strs[1]));
    APIResponse<Void> rsp = reader.connect();
    if (rsp.isSuccess()) {
      Toast.makeText(this, "连接成功", Toast.LENGTH_LONG).show();
      isConnected = true;
    } else {
      Toast.makeText(this, "连接失败", Toast.LENGTH_LONG).show();
    }
  }

  private void startAuto() {
    if (!isConnected) {
      Toast.makeText(this, "请连接设备", Toast.LENGTH_LONG).show();
      return;
    }

    APIResponse<Void> rsp = reader.setWorkMode(IReader.WorkMode.AutoMode);
    if (!rsp.isSuccess()) {
      Toast.makeText(this, "开启自动模式失败", Toast.LENGTH_LONG).show();
    } else {
      Toast.makeText(this, "开启自动模式成功", Toast.LENGTH_LONG).show();
    }
  }

  private void stopAuto() {
    if (!isConnected) {
      Toast.makeText(this, "请连接设备", Toast.LENGTH_LONG).show();
      return;
    }

    APIResponse<Void> rsp = reader.setWorkMode(IReader.WorkMode.CommandMode);
    if (!rsp.isSuccess()) {
      Toast.makeText(this, "停止自动模式失败", Toast.LENGTH_LONG).show();
    } else {
      Toast.makeText(this, "停止自动模式成功", Toast.LENGTH_LONG).show();
    }
  }

  private void setAnt() {
    if (!isConnected) {
      Toast.makeText(this, "请连接设备", Toast.LENGTH_LONG).show();
      return;
    }

    APIResponse<Void> rsp = reader.setWorkAnt((byte) Integer.parseInt(antEdit.getText().toString()));
    if (!rsp.isSuccess()) {
      Toast.makeText(this, "设置天线失败", Toast.LENGTH_LONG).show();
    } else {
      Toast.makeText(this, "设置天线成功", Toast.LENGTH_LONG).show();
    }
  }

  private void listTag() {
    contentEdit.setText("");

    if (!isConnected) {
      Toast.makeText(this, "请连接设备", Toast.LENGTH_LONG).show();
      return;
    }

    //列出之前必须要设置天线
    reader.setWorkAnt((byte) Integer.parseInt(antEdit.getText().toString()));

    // list tag
    APIResponse<List<IReader.Tag>> rsp = reader.list6C(null, (byte) 0, 0, new byte[]{0});
    if  (!rsp.isSuccess()) {
      contentEdit.setText("");
      contentEdit.append(rsp.getErrorMessage());
      return;
    }

    for (int i = 0; i < rsp.result().size() ; i++) {
      IReader.Tag t = rsp.result().get(i);

      //读之前必须要设置天线
      setAnt();
      // read tid
      APIResponse<IReader.Tag> data = reader.read6C(IReader.MemoryBank.TIDMemory, (byte) 0, 12, t.EPC, new byte[]{0, 0, 0, 0});
      if (data.isSuccess()) {
        //Log.d(TAG, "tag: " + t + "tid: " + Util.bytes2HexString(data.result().Data));
        contentEdit.append("epc: " + Util.bytes2HexString(data.result().EPC) +" tid: " + Util.bytes2HexString(data.result().Data)+"\n");
      }
    }
  }


  private void listenAuto() {
//    if (!isConnected) {
//      Toast.makeText(this, "请连接设备", Toast.LENGTH_LONG).show();
//      return;
//    }
//
//    if (isListening) {
//      Toast.makeText(this, "正在监听", Toast.LENGTH_LONG).show();
//      return;
//    }
//
//    isListening = true;
//
//
//    reader.listenCurrentConnectionAutoOutput(new IReader.AutoModeResponseCallback() {
//      @Override
//      public void onResponse(IReader.AutoModelResponseItem item) {
//        Log.d(TAG, "auto output: " + item);
//      }
//    });
  }

  private void stopListenAuto() {
//    if (!isConnected) {
//      Toast.makeText(this, "请连接设备", Toast.LENGTH_LONG).show();
//      return;
//    }
//
//    reader.stopListenCurrentConnectionAutoOutput();
//    isListening = false;
  }


  private void listenUdpAuto() {
    if (isListening) {
      Toast.makeText(this, "正在监听", Toast.LENGTH_LONG).show();
      return;
    }

    isListening = true;

    //监听远程设备
//    IReader.startListenUdp("",5000, autoModelResponseItem -> {
//      Log.d(TAG, "udp auto output: " + autoModelResponseItem);
//      runOnUiThread(new Runnable() {
//        @Override
//        public void run() {
//          contentEdit.append(autoModelResponseItem.EPC+"\n");
//        }
//      });
//    });

    // 监听本地设备
    IReader.startListenUdpAndroidLocal(new IReader.AutoModeResponseCallback() {
      @Override
      public void onResponse(IReader.AutoModelResponseItem autoModelResponseItem) {
      Log.d(TAG, "udp auto output: " + autoModelResponseItem);
      runOnUiThread(new Runnable() {
        @Override
        public void run() {
          contentEdit.append(autoModelResponseItem.EPC+"\n");
        }
      });
      }
    });
  }


  private void stopListenUdpAuto() {
//    IReader.stopListenUdpP32(5000);
    isListening = false;

    //停止监听远程设备
//    IReader.stopListenUdp("",5000);

    //停止监听本地设备
    IReader.stopListenUdpAndroidLocal();
  }
}